package com.sun.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class ThenRunExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程开始");

        // 创建异步任务
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            System.out.println("初始任务执行线程: " + Thread.currentThread().getName());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            return "Hello World";
        });

        // thenRun: 任务完成后执行操作（不关心结果）
        CompletableFuture<Void> runFuture = future.thenRun(() -> {
            System.out.println("thenRun执行线程: " + Thread.currentThread().getName());
            System.out.println("任务已完成，但不关心结果");
        });

        // thenRunAsync: 异步执行后续操作
        CompletableFuture<Void> asyncRunFuture = runFuture.thenRunAsync(() -> {
            System.out.println("thenRunAsync执行线程: " + Thread.currentThread().getName());
            System.out.println("异步后续操作完成");
        });

        // 等待所有任务完成
        asyncRunFuture.get();
        System.out.println("主线程结束");
    }
}
